#!/bin/bash

API_BASE="http://localhost:3002/api/v1"

echo "🛡️ Testing Advanced Security Features"
echo ""

# 1. 登录获取管理员token
echo "1. Login as admin"
LOGIN_RESPONSE=$(curl -s -X POST "$API_BASE/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "testdev@example.com",
    "password": "password123"
  }')

# 提取token
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "❌ Admin login failed"
  echo "Response: $LOGIN_RESPONSE"
  exit 1
fi

echo "✅ Admin login successful"
echo ""

# 2. 获取安全统计
echo "2. Get security statistics"
STATS_RESPONSE=$(curl -s -X GET "$API_BASE/advanced-security/stats" \
  -H "Authorization: Bearer $TOKEN")
echo "Security Stats: $STATS_RESPONSE"
echo ""

# 3. 获取威胁情报
echo "3. Get threat intelligence"
THREAT_RESPONSE=$(curl -s -X GET "$API_BASE/advanced-security/threat-intelligence" \
  -H "Authorization: Bearer $TOKEN")
echo "Threat Intelligence: $THREAT_RESPONSE"
echo ""

# 4. 创建安全策略
echo "4. Create security policy"
POLICY_RESPONSE=$(curl -s -X POST "$API_BASE/advanced-security/policies" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Standard Security Policy",
    "description": "Default security policy for plugin scanning",
    "rules": [
      {
        "id": "rule-1",
        "type": "code_pattern",
        "pattern": "eval\\s*\\(",
        "action": "block",
        "severity": "critical",
        "message": "Use of eval() is prohibited"
      },
      {
        "id": "rule-2",
        "type": "file_pattern",
        "pattern": "\\.exe$",
        "action": "block",
        "severity": "high",
        "message": "Executable files are not allowed"
      }
    ],
    "enabled": true
  }')
echo "Policy Creation: $POLICY_RESPONSE"
echo ""

# 5. 测试综合安全扫描（需要一个真实的插件版本ID）
echo "5. Test comprehensive security scan"
echo "Note: This requires a real plugin version ID. Skipping for now."
echo ""

# 6. 测试特定类型扫描
echo "6. Test specific scan types"
SCAN_TYPES=("vulnerability" "malware" "dependency" "code_quality" "license")

for scan_type in "${SCAN_TYPES[@]}"; do
  echo "Testing $scan_type scan..."
  # 这里需要一个真实的版本ID，暂时跳过
  echo "  Skipped - requires real version ID"
done
echo ""

echo "🎉 Advanced security features testing completed!"
echo ""
echo "📋 Summary of tested features:"
echo "  ✅ Security statistics"
echo "  ✅ Threat intelligence"
echo "  ✅ Security policy creation"
echo "  ⏭️  Security scanning (requires plugin version)"
echo ""
echo "🔧 Next steps:"
echo "  1. Upload a plugin to test actual scanning"
echo "  2. Configure threat intelligence sources"
echo "  3. Set up automated scanning workflows"
